package com.waterai.web;

import com.alibaba.excel.EasyExcel;
import com.waterai.dto.UserDTO;
import com.waterai.entity.User;
import com.waterai.excel.UserExcel;
import com.waterai.service.UserService;
import com.waterai.tools.utils.PageData;
import com.waterai.tools.utils.Result;
import com.waterai.util.ExcelExportUtil;
import com.waterai.util.UploadDataListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
@Api(tags = "用户测试")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("all")
    @ApiOperation("分页查询所有用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pagenum", value = "当前页码，从1开始", dataType = "number", paramType = "query"),
            @ApiImplicitParam(name = "pagesize", value = "每页显示记录数", dataType = "number", paramType = "query"),
    })
    public Result<PageData<UserDTO>> all(@ApiIgnore @RequestParam Map<String, Object> params) {
        return new Result<PageData<UserDTO>>().ok(userService.all(params));
    }

    @PostMapping("add")
    @ApiOperation("添加用户")
    public Result<String> add(@RequestBody User user) {
        try {
            userService.add(user);
            return new Result<String>().ok("新增成功！");
        } catch (Exception e) {
            log.error("新增用户失败，新增失败的用户信息: {},原因：{}", user, e.getMessage());
            return new Result<String>().error(500, "新增失败！");
        }
    }

    @PostMapping("edit")
    @ApiOperation("修改用户")
    public Result<String> edit(@RequestBody User user) {
        try {
            userService.edit(user);
            return new Result<String>().ok("修改成功！");
        } catch (Exception e) {
            log.error("修改用户失败，修改失败的用户信息: {}, 原因：{}", user, e.getMessage());
            return new Result<String>().error(500, "修改失败！");
        }
    }

    @GetMapping("delete/{id}")
    @ApiOperation("删除用户")
    public Result<String> delete(@PathVariable Long id) {
        try {
            userService.delete(id);
            return new Result<String>().ok("删除成功！");
        } catch (Exception e) {
            log.error("删除用户失败，删除失败的用户id: {}，原因：{}", id, e.getMessage());
            return new Result<String>().error(500, "删除失败！");
        }
    }

    @PostMapping("delete")
    @ApiOperation("批量删除用户(用于勾选多数据的删除)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "传要删除的多个id的数组", dataType = "array", paramType = "body")
    })
    public Result<String> delete(@ApiIgnore @RequestBody String[] ids) {
        int successful = 0;
        for (String id : ids) {
            try {
                userService.delete(Long.valueOf(id));
                successful++;
            } catch (Exception e) {
                log.error("删除用户失败，删除失败的用户id: {}，原因：{}", id, e.getMessage());
            }
        }
        if (successful == ids.length) {
            return new Result<String>().ok("成功删除，所选记录！");
        }
        return new Result<String>().ok(String.format("成功删除：%s个，删除失败：%s个", successful, ids.length - successful));
    }

    @PostMapping("import")
    @ApiOperation("excel导入用户信息！")
    public Result<String> importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), UserExcel.class, new UploadDataListener<>(userService, 200)).sheet().doRead();
            return new Result<String>().ok("导入成功！");
        } catch (Exception e) {
            log.error("导入失败，原因: {}", e.getMessage());
            return new Result<String>().error("导入失败！");
        }
    }

    @PostMapping("export")
    @ApiOperation("导出所选用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "传要导出的多个id的数组，默认空数组导出所有数据！", dataType = "array", paramType = "body")
    })
    public void exportExcel(@ApiIgnore @RequestBody String[] ids, HttpServletResponse response) {
        try {
            List<UserDTO> userDTOS = userService.queryByIds(ids);
            ExcelExportUtil.export(response, userDTOS, UserExcel.class, "用户基本信息", "基本信息");
        } catch (Exception e) {
            log.error("导出失败，原因：{}", e.getMessage());
        }
    }
}
